package cn.ilikes.tools.nosql.jpa.metadatas.processor.processores;

import javax.persistence.Table;

import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;
import cn.ilikes.tools.nosql.jpa.annotations.Index;
import cn.ilikes.tools.nosql.jpa.metadatas.EntityMetaData;
import cn.ilikes.tools.nosql.jpa.metadatas.elements.EntityIndex;
import cn.ilikes.tools.nosql.jpa.metadatas.processor.validators.EntityIndexValidator;
import cn.ilikes.tools.nosql.jpa.metadatas.processor.validators.EntityTableAndEntityValidator;
import cn.ilikes.tools.nosql.jpa.metadatas.processor.validators.EntityValidatorException;

/*
 * 对entity class 
 */
public class EntityTableProcessors implements Processors {

	private Logger logger = Loggerfactory.instance(EntityTableProcessors.class);

	private EntityTableAndEntityValidator entityTableAndEntityValidator = new EntityTableAndEntityValidator();

	private EntityIndexValidator entityIndexValidator = new EntityIndexValidator();

	@Override
	public void validators(Class<?> clazz, EntityMetaData metadata) throws EntityValidatorException {
		if (Loggerfactory.isdebug(logger))
			logger.debug("start  validators    clazz " + clazz.getName() + "  table   ");
		try {
			entityTableAndEntityValidator.entityValidator(clazz, metadata);
			entityIndexValidator.entityValidator(clazz, metadata);
		} catch (EntityValidatorException e) {
			throw new EntityValidatorException(e);
		}
	}

	@Override
	public void processors(Class<?> clazz, EntityMetaData metadata) throws ElementProcessorException {
		if (Loggerfactory.isdebug(logger))
			logger.debug("start  processors entity  clazz " + clazz.getName() + " table  ");
		validators(clazz, metadata);
		processorsEntity(clazz, metadata);

	}

	private void processorsEntity(Class<?> clazz, EntityMetaData metadata) {
		if (Loggerfactory.isdebug(logger))
			logger.debug("start  processors entity  clazz " + clazz.getName() + " table  ");
		Table table = clazz.getAnnotation(Table.class);

		String entityTableName = table.name();

		metadata.setEntityTableName(entityTableName);

		metadata.setEntityName(clazz.getSimpleName());

		String schema = table.schema();

		metadata.setSchema(schema);

		metadata.setEntityClazz(clazz);

		metadata.setInterfaces(clazz.getInterfaces());
		//paser index 
		Index index = clazz.getAnnotation(Index.class);

		EntityIndex entityIndexImpl = new EntityIndex();

		metadata.setEntityIndex(entityIndexImpl);

		if (index != null) {//have @index
			String indexName = index.name();
			if (indexName == null || indexName.isEmpty())
				indexName = metadata.getEntityClazz().getSimpleName();
			entityIndexImpl.setIndexName(indexName);
			entityIndexImpl.setIndexable(index.index().equals(Index.index.yes) ? true : false);
		} else {//无@index
			entityIndexImpl.setIndexName(metadata.getEntityClazz().getSimpleName());
			entityIndexImpl.setIndexable(true);

		}
	}

}
